package peer.share;

import java.io.IOException;
import java.io.RandomAccessFile;

import peer.tools.Mdb;


public class PieceTemp {
	long creatTime=0;
	Mdb mdb;
	int pieceNum;
	static int globalOffset=0;
	long offset;
	int length;
	PieceTemp(Mdb mdb,int pieceNum,byte[]data) throws IOException{
		this.mdb=mdb;
		this.pieceNum=pieceNum;
		this.length=data.length;
		creatTime=System.currentTimeMillis();
		offset=save(data);
		data=null;
	}
	
	synchronized static long save(byte[] data) throws IOException{
		long offset=globalOffset;
		RandomAccessFile ra=new RandomAccessFile(peer.Config.tempPath,"rw");
		ra.seek(globalOffset);
		ra.write(data);
		ra.close();
		globalOffset+=data.length;
		if(globalOffset>1024*1024*100){
			globalOffset=0;
		}
		return offset;
	}
	
	byte[] getData() throws IOException{
		RandomAccessFile ra=new RandomAccessFile(peer.Config.tempPath,"r");
		byte[] data=new byte[length];
		ra.seek(offset);
		ra.read(data);
		ra.close();
		return data;
	}
	
}
